package com.uwlaser.webservice.exception;

import com.uwlaser.socket.exception.TcpSocketCodeErrorException;
import com.uwlaser.socket.exception.TcpSocketException;
import lombok.Data;

/**
 * @Author QZK
 * @Description WebService异常处理类
 * @Date 2022-12-05-16:19
 * @Version 1.0
 */
@Data
public class WebServiceException extends Exception {

    private static final String type = "WebService";

    /**
     * 地址
     */
    private String url;
    /**
     * 方法名称
     */
    private String methodName;

    /**
     * 请求体参数
     */
    private String bodyParams;

    /**
     * 请求头参数
     */
    private String headerParams;

    /**
     * 描述
     */
    private String describe;

    /**
     * 请求结果
     */
    private String requestResult;

    public WebServiceException(String message) {
        super(handleMsgLength(message));
    }

    public WebServiceException(String message, String describe) {
        super(handleMsgLength(message));
        this.describe = describe;
    }

    public WebServiceException(String url, String methodName, String bodyParams, String headerParams, String describe,String message, String requestResult) {
        super(handleMsgLength(message));
        this.url = url;
        this.methodName = methodName;
        this.bodyParams = bodyParams;
        this.headerParams = headerParams;
        this.describe = describe;
        this.requestResult = requestResult;
    }

    /**
     * 处理异常
     * @return
     */
    public static WebServiceException handleException(String url, String methodName, String bodyParams, String headerParams, Exception e){
        WebServiceException te = null;
        if(e instanceof WebServiceException){
            //统一设置异常数据
            te = (WebServiceException) e;
            te.setUrl(url); //地址
            te.setMethodName(methodName); //方法
            te.setBodyParams(bodyParams); //请求体参数
            te.setHeaderParams(headerParams); // 请求头参数
        } else {
            //其他异常默认按照代码异常和数据异常处理
            te = new WebServiceCodeErrorException(url,methodName,bodyParams,headerParams,"调用WebService接口发生异常："+e.getMessage());
        }
        return te;
    }

    /**
     * 处理消息长度
     * @return
     */
    private static String handleMsgLength(String message){
        if(message != null && message.length() > 500){
            message = message.substring(0,500);
        }
        return "【请求外部系统异常】" +  message;
    }
}